<template>
  <div>
    <div>
      <el-input v-model="search" placeholder="请输入内容"></el-input>
      <el-button type="primary" @click="searchItem">查询</el-button>
      <el-button type="primary" @click="add">添加</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column prop="hobby" label="爱好"> </el-table-column>
      <el-table-column prop="opera" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="edit(scope)" class="edit"
            >修改</el-button
          >
          <el-popconfirm title="确定删除吗？" @confirm="deleteItem(scope)">
            <el-button slot="reference" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <add-or-edit
      :visible="visible"
      :title="title"
      :obj="obj"
      @close="close"
      @addItem="addItem"
      @editItem="editItem"
    ></add-or-edit>
  </div>
</template>

<script>
import AddOrEdit from '../AddOrEdit/AddOrEdit'
export default {
  components: {
    'add-or-edit': AddOrEdit
  },
  data() {
    return {
      search: '',
      tableData: [
        {
          id: 1,
          name: 'zs',
          gender: '男',
          hobby: ['打篮球']
        }
      ],
      visible: false,
      title: '',
      obj: {}
    }
  },
  methods: {
    close() {
      this.visible = false
    },
    add() {
      this.obj = {}
      this.title = '新增'
      this.visible = true
    },
    edit(item) {
      this.obj = JSON.parse(JSON.stringify(item.row))

      this.title = '编辑'
      this.visible = true
    },
    deleteItem(item) {
      let index = this.tableData.findIndex((res) => res.id === item.row.id)
      this.tableData.splice(index, 1)
    },
    addItem(data) {
      let id = this.tableData.length + 1
      data.id = id
      this.tableData.unshift(data)
    },
    editItem(data) {
      let index = this.tableData.findIndex((item) => item.id === data.id)
      this.tableData.splice(index, 1, data)
    },
    searchItem() {
      this.tableData = this.tableData.filter((res) => {
        return res.name === this.search
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 200px;
}

.el-table {
  margin-top: 20px;
}

.edit {
  margin-right: 5px;
}
</style>
